package com.netease.xone.widget;

import android.content.Context;
import android.util.AttributeSet;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.Transformation;
import android.widget.Gallery;

public class ScrollGallery extends Gallery {

	private static final int AUTO_CHANGE_TIME = 5000;
	private boolean isAutoScroll = false;

	private Runnable mAutoRunnable = new Runnable() {
		@Override
		public void run() {
			scrollRight();
			postDelayed(this, AUTO_CHANGE_TIME);
		}
	};

	public ScrollGallery(Context context) {
		this(context, null);
	}

	public ScrollGallery(Context context, AttributeSet attrs) {
		super(context, attrs);
		init();
	}

	private void init() {
		setAnimationDuration(1000);
		setSoundEffectsEnabled(false);
		setFadingEdgeLength(0);
	}

	@Override
	protected boolean getChildStaticTransformation(View child, Transformation t) {
		return false;
	}

	@Override
	public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
			float velocityY) {
		if (e2.getX() > e1.getX()) {
			scrollLeft();
		} else {
			scrollRight();
		}
		return true;
	}

	private void scrollLeft() {
		onKeyDown(KeyEvent.KEYCODE_DPAD_LEFT, null);
	}

	private void scrollRight() {
		onKeyDown(KeyEvent.KEYCODE_DPAD_RIGHT, null);
	}

	@Override
	protected void onDetachedFromWindow() {
		if (isAutoScroll)
			stopAutoScroll();
		super.onDetachedFromWindow();
	}

	@Override
	public void onWindowFocusChanged(boolean hasWindowFocus) {
		super.onWindowFocusChanged(hasWindowFocus);
		if (isAutoScroll) {
			if (hasWindowFocus) {
				startAutoScroll();
			} else {
				stopAutoScroll();
			}
		}
	}

	private void startAutoScroll() {
		removeCallbacks(mAutoRunnable);
		postDelayed(mAutoRunnable, AUTO_CHANGE_TIME);
	}

	private void stopAutoScroll() {
		removeCallbacks(mAutoRunnable);
	}

	public void setAutoScroll(boolean autoScroll) {
		if (autoScroll != isAutoScroll) {
			isAutoScroll = autoScroll;
			if (isAutoScroll) {
				startAutoScroll();
			} else {
				stopAutoScroll();
			}
		}
	}
}
